<?php

class ZFKiller_Form_Element_Text_Date extends Glitch_Form_Element_Text_Date {

	public function __construct($spec, $options = null) {
		$options['type'] = Glitch_Form_Element_Text::FIELD_DATE;

		ZFKiller_Form_Element::formatDefaultOptions($spec, $options);
		parent::__construct($spec, $options);

		ZFKiller_Form_Element::formatElementAsDate($this);
		$this->addValidator(new Zend_Validate_Date());
	}

	public function getValue() {
		switch (ZFKiller_Form::getValueType()) {
			case ZFKiller_Form::GET_VALUE_TYPE_DB:
				return $this->getValueDb();
				break;
			case ZFKiller_Form::GET_VALUE_TYPE_USER:
				return $this->getValueUser();
				break;
			default:
				return $this->getValueUser();
				//return $this->getUnfilteredValue();
				break;
		}
	}

	public function getValueDb() {
		$date = $this->getUnfilteredValue();
		if ($date instanceof Zend_Date) {
			$date = new Zend_Date($this->getUnfilteredValue(), Zend_Locale_Format::getDateFormat());
			return $date->getIso();
		}
		return null;
	}

	public function getValueUser() {
		$date = $this->getUnfilteredValue();

		if ($date instanceof Zend_Date) {
			return $date->get(Zend_Date::DATES);
		}

		return $date;
	}

	public function setValue($date) {
		if (Zend_Date::isDate($date)) {
			$date = new Zend_Date($date, Zend_Locale_Format::getDateFormat());
		}
		elseif (is_numeric($date)) {
			$date = new Zend_Date($date);
		}
		elseif (false !== ($timestamp = strtotime($date))) {
			$date = new Zend_Date($timestamp);
		}

		parent::setValue($date);
		return $this;
	}

}